package com.forum.service.impl;

import com.forum.service.UserCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserCacheServiceImpl implements UserCacheService {

    private final RedisTemplate<String, Object> redisTemplate;
    private static final String USER_INFO_CACHE_KEY = "user:info:";
    private static final long USER_INFO_CACHE_TTL = 3600L; // 1小时过期

    @Override
    public Map<String, Object> getUserInfo(Long userId) {
        String cacheKey = USER_INFO_CACHE_KEY + userId;
        Object userInfo = redisTemplate.opsForValue().get(cacheKey);
        return userInfo != null ? (Map<String, Object>) userInfo : null;
    }

    @Override
    public void updateUserCache(Long userId, Map<String, Object> userInfo) {
        String cacheKey = USER_INFO_CACHE_KEY + userId;
        redisTemplate.opsForValue().set(cacheKey, userInfo, USER_INFO_CACHE_TTL, TimeUnit.SECONDS);
        log.info("Updated user cache for userId: {}", userId);
    }

    @Override
    public void deleteUserCache(Long userId) {
        String cacheKey = USER_INFO_CACHE_KEY + userId;
        redisTemplate.delete(cacheKey);
        log.info("Deleted user cache for userId: {}", userId);
    }
} 